/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.ipti.br.tag.dao;

import org.ipti.br.tag.entity.AddInfoPersonage;
import org.ipti.br.tag.entity.AddInfoPersonage_;
import org.ipti.br.tag.entity.AdditionalInfoType;
import org.ipti.br.tag.entity.Personage_;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

/**
 *
 * @author root
 */
@Stateless
public class AddInfoPersonageFacade extends AbstractFacade<AddInfoPersonage> {

    @PersistenceContext(unitName = "TAG2PU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public AddInfoPersonageFacade() {
        super(AddInfoPersonage.class);
    }

    @Override
    public void create(AddInfoPersonage addInfoPersonage) {
        getEntityManager().persist(addInfoPersonage);
    }

    @Override
    public void edit(AddInfoPersonage addInfoPersonage) {
        addInfoPersonage.setSerialNumber(null);

        getEntityManager().merge(addInfoPersonage);
    }

    public void editForSynchronization(AddInfoPersonage addInfoPersonage) {
        getEntityManager().merge(addInfoPersonage);
    }

    public List<AddInfoPersonage> findAddInfoPerPersonage(Long personageID) {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<AddInfoPersonage> cq = cb.createQuery(AddInfoPersonage.class);
        Root<AddInfoPersonage> from = cq.from(AddInfoPersonage.class);
        Predicate predicate = cb.equal(from.get(AddInfoPersonage_.personage).get(Personage_.id), personageID);
        cq.where(cb.and(predicate));

        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<AdditionalInfoType> findAddInfoWithPersonage() {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery cq = cb.createQuery(AddInfoPersonage.class);
        Root from = cq.from(AddInfoPersonage.class);
        cq.select(from.get(AddInfoPersonage_.additionalInfoType));
        cq.where(cb.isNotNull(from.get(AddInfoPersonage_.personage)));
        cq.distinct(true);

        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<AddInfoPersonage> findAddInfoWithoutPersonage() {
        CriteriaBuilder cb = getEntityManager().getCriteriaBuilder();
        CriteriaQuery<AddInfoPersonage> cq = cb.createQuery(AddInfoPersonage.class);
        Root<AddInfoPersonage> from = cq.from(AddInfoPersonage.class);
        Predicate predicate = cb.isNull(from.get(AddInfoPersonage_.personage));
        cq.where(cb.and(predicate));

        return getEntityManager().createQuery(cq).getResultList();
    }
}